<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <style>
      /*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
      ::-webkit-scrollbar {
        width: 5px;
        height: 5px;
        background-color: #F5F5F5;
      }

      /*定义滚动条轨道 内阴影+圆角*/
      ::-webkit-scrollbar-track {
        box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
        -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
        border-radius: 10px;
        background-color: #F5F5F5;
      }

      /*定义滑块 内阴影+圆角*/
      ::-webkit-scrollbar-thumb {
        border-radius: 10px;
        box-shadow: inset 0 0 6px rgba(0, 0, 0, .1);
        -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .1);
        /*滚动条的颜色*/
        background-color: #00BFFF;
      }






      html,body{
      	width: 100%;
      	height: 100%;
      	padding-bottom:15px;
      }
      *{
      	padding: 0;
      	margin: 0;
      	box-sizing: border-box;
      }

      .preview_main_page {
        display: flex;
        width: 100%;
        height: 100%;
        flex-direction: column;
      }

      /*场景部分*/
      .preview_main_page_center {
        height: 100%;
        flex-grow: 1;
        display: flex;
        justify-content: flex-start;
        align-items: top;
        padding-top: 15px;
        flex-direction: column;
        overflow: auto;
      }


      .layui-btn {
        float: right;
        background-color: #409eff !important;
      }

      /* #hardwareform{
        border:1px solid red;
    } */

      #hardwareform .layui-form-item {
        margin-right: 80px;
        margin-bottom: 10px;
      }

      .layui-form-item .layui-input-block {
        margin-left: 20px;
        /* border:1px solid red; */
      }

      #hardwareform .layui-form-select {
        width: 240px !important;
      }

      #hardwareform .layui-input {
        width: 240px !important;
        padding-right: 5px !important;
        margin-left: 5px !important;
      }

      #hardwareform .layui-form-label {
        width: auto;
        min-width:57px;
        max-width: 100px;
        text-align: right;
      }

      #hardwareform .layui-form-select dl {
        /* min-height:640px!important;
		  height:640px!important; */
        margin-left: 5px;
        max-height: 570px !important;
      }

      .layui-form-select dl dt,
      .layui-form-select dl dd {
        line-height: 26px !important;
      }

      /* .layui-form-select dl dd.layui-select-tips{
			把第一个下拉提示框选项不显示
			height:0;
			line-height: 0;
			overflow: hidden;
			margin-top:0;
		} */

      .layui-select-disabled .layui-disabled {
        background-color: #ccc;
      }


      #hardwareform .layui-form-item {
        display: inline-block;
      }


      #sensorform {
        width: 94%;
        /* height: 560px; */
        /* height:calc(100% - 140px)!important; */
        height:auto;
        margin: 0 auto;
        /* border:1px solid red; */
      }

      .sensorBox {
        /* width:calc(100% - 120px)!important; */
        width:100%!important;
        /* height: 560px; */
        /* height:calc(100% - 140px)!important; */
        height:auto;
        display: flex;
        justify-content: space-between;
        align-items: center;
        /* padding-top:15px; */
        flex-direction: column;
        overflow: auto;
        /* border:1px solid red; */
      }

      .layui-form-radio {
        display: inline-block;
        width: 240px !important;
        text-align: left;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        /* border:1px solid red;*/
      }

      /* .sensorItem{
       display:inline-block;
       width:180px!important;
       text-align:left;
    } */
    </style>
    <!--layui框架-->
    <script src="js/plugIn/jquery/jquery.min.js"></script><!--jquery 要在layui之前，这样layui就不会加载内部的jquery-->
    <link rel="stylesheet" href="js/plugIn/layui-master/src/css/layui.css">
    <script src="js/plugIn/layui-master/src/layui.js"></script>
    <script src="config/InitConfig.js"></script>
    <script src="js/common/tool.js"></script>
  </head>
  <body>
    <div class="preview_main_page">
      <div class="preview_main_page_center">
        <form class="layui-form" action="" id="hardwareform" lay-filter="hardwareform">

        </form>
        <form class="layui-form" action="" id="sensorform" lay-filter="sensorform">

        </form>


      </div>
    </div>
  </body>
  <script>
    //var baseUrl="http://yklink.net:36002";
    var baseUrl = localStorage.getItem("baseURL");
    var index = parent.layer.getFrameIndex(window.name);
    var initConfig;
    var initjson;
    var form;
    layui.use(['form'], function() {
      form = layui.form;
      initConfig = new InitConfig();
      //读取配置文件
      $.ajaxSettings.async = false; //设置getJson同步
      $.getJSON("config/init.json", function(data) {
        initjson = data;
      });
      $.ajaxSettings.async = true; //设置getJson异步
      var hardwareSelectItemsObj = initjson.hardwareSelectItems; //配置项
      //初始化下拉框选择
      var hardwareSelectHtmlStr = initHardwareSelectHtml(hardwareSelectItemsObj, '');

      hardwareSelectHtmlStr +=

        '<div class="layui-form-item" style="margin-right:0;">' +
        '<div class="layui-input-block">' +
        '<input type="button" onclick="okClick()" class="layui-btn" value="确定"/>' +
        '</div>' +
        '</div>';

      $("#hardwareform").html(hardwareSelectHtmlStr);
      form.render('select', 'hardwareform');

      // 给下拉选择框添加监听
      form.on('select(HardwareSelect_select)', function(data) {
        var select_id = data.elem.id;
        var select_value = data.value.split("##")[0];
        var select_value_type = data.value.split("##")[1];
        var changeFunction = data.elem.attributes.changeFunction.value;
        if (changeFunction == "") {
          return;
        }

        //在处理下级select前，先将所有下级的select清空
        emptyNextsSelect(select_id, hardwareSelectItemsObj);

        // 通过当前id 找到下级id
        var nextSelectId = getNextSelectId(select_id, hardwareSelectItemsObj, select_value_type);
        //根据当前选择的值查找下级的数据
        var nexttSelectItem = eval("initConfig." + changeFunction + "(select_value,select_value_type)");
        if (select_id == "cj") {
          //console.log(nexttSelectItem);
          initSensorList(nexttSelectItem, true);
        }
        //渲染下级select的数据
        if (select_id == "cj" || (select_id == "sb" && select_value_type == 1)) {
          var nextSelectHtml = '<option value="">请选择,可输入关键字检索</option>';
          if (nexttSelectItem != '') {
            for (var z = 0; z < nexttSelectItem.length; z++) {
              var hardwareObj = nexttSelectItem[z];
              if (z == 0 && nextSelectId == 'cj') {
                nextSelectHtml += '<option  value="' + hardwareObj.code + '##' + hardwareObj.type +
                  '" selected>' + hardwareObj.name + '</option>';
                var getCgq = initConfig.getCgq;
                var sensorItem = getCgq(hardwareObj.code, hardwareObj.type);
                initSensorList(sensorItem, true);
              } else {
                nextSelectHtml += '<option  value="' + hardwareObj.code + '##' + hardwareObj.type + '">' +
                  hardwareObj.name + '</option>';
              }
              //nextSelectHtml += '<option  value="'+ hardwareObj.code +'##'+ hardwareObj.type+ '">' + hardwareObj.name + '(' + hardwareObj.code + ')</option>';

            }
          }
          $("#" + nextSelectId).html(nextSelectHtml);
          if (nextSelectId == "cj" && (nexttSelectItem == '' || !nexttSelectItem.length)) {
            $("#sensorform").html("");
          }
        } else if (select_id == "sb" && select_value_type == 2) {
          var getCgq = initConfig.getCgq;
          var sensorItem = getCgq(select_value, select_value_type);
          initSensorList(sensorItem, true);
        }



        //当前id 如果 和 下级id之间有跳跃的，中间的下拉框要要置灰
        setSelectDisabled(select_id, nextSelectId, hardwareSelectItemsObj);


        //$("#cgqItem").hide();
        form.render('select', 'hardwareform');





      });
      //----------------以下回显处理(需要的时候打开注释)------------------
      //获取url地址上的hardware_id参数
      var hardware_id = $_GET.hardware_id;

      if (hardware_id == "") {
        //如果组件还未绑定数据点，默认显示该项目下的第一个设备的第一个数据点并反推回显；
        var allId = getPrentId(localStorage.getItem('firstAtSensor'));
        echoOperation(allId, hardwareSelectItemsObj);
      } else {
        //如果已绑定的回显处理；
        var allId = getPrentId(hardware_id);
        echoOperation(allId, hardwareSelectItemsObj);
      }

      //----------------以下回显处理end------------------

    });
    //通过传感器的id 获取父级所有id 以如下格式返回，包含本传感器的id
    /*var parendAllId ={
     nodeId:11,  第一级id
     type:1,   没有可以是''  但节点不能少
     child:{
     nodeId:21,第二级id
     type:1,
     child:{
     nodeId:21,第三级id
     type:1,
     child:{
     nodeId:123,第四级id
     type:1
     }
     }
     }
     }*/

    function getPrentId(hardware_id) {
      console.log(hardware_id);
      if (!hardware_id) {
        return
      }
      /**
         开发人员在这里写Ajax从后台请求 返回以下格式的数据 这里写死
       * */
      var parendAllId = {};
      $.ajax({
        type: "post",
        async: false, //同步，等待结果后再执行后面的数据
        url: baseUrl + '/api/sensor/info',
        dataType: "json",
        data: {
          'id': hardware_id,
          'token': localStorage.getItem("attoken")
        },
        success: function(data) {
          if (data && data.result == 'success') {
            // console.log(data.data);
            if (data.data.equip_type == 1) { //子设备设备
              parendAllId = {
                nodeId: data.data.equip_id,
                type: data.data.equip_type,
                child: {
                  nodeId: data.data.sgroup_id,
                  type: '',
                  child: {
                    nodeId: data.data.sensor_code,
                    type: data.data.type
                    //child:{
                    // 	//  nodeId:'',
                    // 	//  type:''
                    //}
                  }
                }
              };
            //直连设备和虚拟设备
            } else if (data.data.equip_type >= 2) { //直连设备
              parendAllId = {
                nodeId: data.data.equip_id,
                //直连设备和虚拟设备都没有分组，统一取2
                type:2,
                child: {
                  nodeId: data.data.sensor_code,
                  type: data.data.type
                  //child:{
                  // 	//  nodeId:'',
                  // 	//  type:''
                  //}
                }

              };
            } else {
              console.log("不支持的设备类型")
            }
            //console.log(parendAllId);
          } else {
            alert(data.msg);

          }

        },
        error: function(jqXHR) {
          console.log("发生错误：" + jqXHR.status);
        }
      });
      return parendAllId;

    }
    var id_i = 1; //记录 硬件id的层级
    function echoOperation(idObj, hardwareSelectItemsObj) {
      var currentId = 0;
      //console.log(idObj);
      //if(idObj.nodeId.indexOf('&')>=0){
      //currentId = idObj.nodeId.split('&')[0];
      //}else{
      currentId = idObj.nodeId;
      //}
      var childIdObj = idObj.child;
      var currentType = idObj.type;
      var curentidSelectItemsObj = getCurentSelectOption(hardwareSelectItemsObj, id_i); //当前下拉的配置

      echoOperationTow(currentId, currentType, curentidSelectItemsObj, hardwareSelectItemsObj);
      if (currentType == 2) {
        id_i = id_i + 2;
      } else {
        id_i++;
      }

      if (typeof(childIdObj) == "undefined") {
        return;
      } else {
        echoOperation(childIdObj, hardwareSelectItemsObj);
      }

    }

    function echoOperationTow(currentId, currentType, curentidSelectItemsObj, hardwareSelectItemsObjAll) {
      var select_id = curentidSelectItemsObj.selectId;
      var selectName = curentidSelectItemsObj.selectName;
      var initFunction = curentidSelectItemsObj.initFunction;
      var changeFunction = curentidSelectItemsObj.changeFunction;
      //	var child = hardwareSelectItems.child;

      //获取下级的数据。
      //在处理下级select前，先将所有下级的select清空
      emptyNextsSelect(select_id, hardwareSelectItemsObjAll);

      // 通过当前id 找到下级id
      var nextSelectId = getNextSelectId(select_id, hardwareSelectItemsObjAll, currentType);
      //根据当前选择的值查找下级的数据
      var nexttSelectItem = [];
      if (changeFunction != '') {
        nexttSelectItem = eval("initConfig." + changeFunction + "(currentId,currentType)");
        if (nextSelectId == 'cgq') {
          //console.log(nexttSelectItem)
          initSensorList(nexttSelectItem);

        }
      }

      //渲染下级select的数据
      var nextSelectHtml = '<option value="">请选择,可输入关键字检索</option>';
      if (nexttSelectItem != '') {
        for (var z = 0; z < nexttSelectItem.length; z++) {
          var hardwareObj = nexttSelectItem[z];
          //nextSelectHtml += '<option  value="'+ hardwareObj.code +'##'+ hardwareObj.type+ '">' + hardwareObj.name + '(' + hardwareObj.code + ')</option>';
          nextSelectHtml += '<option  value="' + hardwareObj.code + '##' + hardwareObj.type + '">' + hardwareObj.name +
            '</option>';
        }
      }


      if (typeof(nextSelectId) != "undefined") {
        $("#" + nextSelectId).html(nextSelectHtml);
      }




      //当前id 如果 和 下级id之间有跳跃的，中间的下拉框要要置灰
      try {
        setSelectDisabled(select_id, nextSelectId, hardwareSelectItemsObjAll);
      } catch (e) {

      }


      $("#" + select_id).val(currentId + '##' + currentType);
      if (select_id == 'cgq') {
        form.val("sensorform", {
          "sensor": currentId + '##' + currentType
        });
        form.render('radio', 'sensorform');
      }
      form.render('select', 'hardwareform');

    }
    var id_j = 1; //记录下拉列表的层级
    // 获得当前值对于的下拉列表配置
    function getCurentSelectOption(hardwareSelectItemsObj, index) {
      var selectId = hardwareSelectItemsObj.selectId;
      var selectName = hardwareSelectItemsObj.selectName;
      var initFunction = hardwareSelectItemsObj.initFunction;
      var changeFunction = hardwareSelectItemsObj.changeFunction;
      var child = hardwareSelectItemsObj.child;

      if (id_j == index) {
        id_j = 1;
        return hardwareSelectItemsObj;
      } else {
        id_j++;
        return getCurentSelectOption(child, index);
      }

    }

    function initHardwareSelectHtml(hardwareSelectItems, selectHtml) {
      var selectId = hardwareSelectItems.selectId;
      var selectName = hardwareSelectItems.selectName;
      var initFunction = hardwareSelectItems.initFunction;
      var changeFunction = hardwareSelectItems.changeFunction;
      var child = hardwareSelectItems.child;

      var initSelectItem = '';
      if (typeof(initFunction) != "undefined") {
        var selectOneWhere = parent.selectOneWhere;
        initSelectItem = eval("initConfig." + initFunction + "(selectOneWhere)");
      }


      var HardwareSelectHtml = selectHtml +
        '<div class="layui-form-item" id="' + selectId + 'Item"' + '>' +
        '<label class="layui-form-label">' + selectName + '</label>' +
        '<div class="layui-input-inline">' +
        '<select lay-search changeFunction="' + changeFunction + '"  id="' + selectId + '" name="' + selectId +
        '"  lay-filter="HardwareSelect_select">' +
        '<option value="">请选择,可输入关键字检索</option>';
      if (initSelectItem != '') {
        for (var z = 0; z < initSelectItem.length; z++) {
          var hardwareObj = initSelectItem[z];
          //HardwareSelectHtml += '<option  value="'+hardwareObj.code+'##'+ hardwareObj.type+'">' + hardwareObj.name + '(' + hardwareObj.code + ')</option>';
          HardwareSelectHtml += '<option  value="' + hardwareObj.code + '##' + hardwareObj.type + '">' + hardwareObj
            .name + '</option>';
        }
      }
      HardwareSelectHtml += '</select>' +
        '</div>' +
        '</div>';
      if (typeof(child) == "undefined") {
        return HardwareSelectHtml;
      } else {
        return initHardwareSelectHtml(child, HardwareSelectHtml);
      }
    }


    //初始化变量列表函数
    function initSensorList(sensorArray, setDefault = false) {
      $("#sensorform").html("");
      $("#cgqItem").hide();
      if (!sensorArray.length) {
        return;
      }
      var htmlSensorStr = '<div class="layui-form-item ">' +
        // '<label class="layui-form-label" style="width:100px;">数据点选择：</label>' +
        '<div class="layui-input-inline sensorBox" >';
      for (var z = 0; z < sensorArray.length; z++) {
        var sensorObj = sensorArray[z];
        htmlSensorStr += '<input type="radio" name="sensor" lay-filter="sensor" class="sensorItem" value="' + sensorObj
          .code + '##' + sensorObj.type + '" title="' + sensorObj.name + '">';
        //HardwareSelectHtml += '<option  value="'+hardwareObj.code+'##'+ hardwareObj.type+'">' + hardwareObj.name + '(' + hardwareObj.code + ')</option>';
        //  HardwareSelectHtml += '<option  value="'+hardwareObj.code+'##'+ hardwareObj.type+'">' + hardwareObj.name + '</option>';
      }
      htmlSensorStr += '</div>' +
        '</div>';
      $("#sensorform").html(htmlSensorStr);
      if (setDefault) {
        form.val("sensorform", {
          "sensor": sensorArray[0].code + '##' + sensorArray[0].type
        });
        $("#cgq").val(sensorArray[0].code + '##' + sensorArray[0].type);
        form.render('select', 'hardwareform');
      }
      form.on('radio(sensor)', function(data) {
        //console.log(data.value);
        $("#cgq").val(data.value);
        form.render('select', 'hardwareform');
      });
      form.render('radio', 'sensorform');

    }




    /**
     * 通过当前id找到下级id
     * @param selectIdO，当前id
     * @param hardwareSelectItemsObj 下拉列表配置项
     */
    function getNextSelectId(selectIdO, hardwareSelectItemsObj, select_value_type) {

      var selectId = hardwareSelectItemsObj.selectId;
      var child = hardwareSelectItemsObj.child;
      var jump = hardwareSelectItemsObj.jump;
      var jump_attribute = jump.attribute;
      var jump_operator = jump.operator;
      var jump_value = jump.value;
      var jump_jupmTarget = jump.jupmTarget;

      if (jump != "" && selectIdO == selectId) {
        if (select_value_type != "") {
          if (eval("" + select_value_type + jump_operator + jump_value)) {
            return jump_jupmTarget;
          }
        }
      }


      if (selectIdO == selectId) {
        if (typeof(child) != "undefined") {
          return child.selectId;
        }

      } else {
        return getNextSelectId(selectIdO, child, select_value_type);
      }

    }
    /**
     * 当前selectid 如果 和 下级selectid之间有跳跃的，中间的下拉框要要置灰
     * @param currentSelectId
     * @param nextSelectId
     * @param hardwareSelectItemsObj
     */
    function setSelectDisabled(currentSelectId, nextSelectId, hardwareSelectItemsObj) {
      var selectId = hardwareSelectItemsObj.selectId;
      var child = hardwareSelectItemsObj.child;
      if (currentSelectId == selectId) {
        //得到需要置灰的id数组
        var disabledSelectIdArray = getSelectDisabledIds(nextSelectId, child, new Array());
        //置灰
        if (disabledSelectIdArray.length > 0) {
          for (var i = 0; i < disabledSelectIdArray.length; i++) {
            var disabledId = disabledSelectIdArray[i];
            $('#' + disabledId).attr("disabled", true);
            //layui.form.render('select','hardwareform');
          }
        }

      } else {
        setSelectDisabled(currentSelectId, nextSelectId, child)
      }

    }
    /**返回需要置灰的id
     * 当前selectid 如果 和 下级selectid之间有跳跃的，返回中间的下拉框的id
     * @param currentSelectId
     * @param nextSelectId
     * @param hardwareSelectItemsObj
     */
    function getSelectDisabledIds(nextSelectId, hardwareSelectItemsObj, selectIdArray) {
      var selectId = hardwareSelectItemsObj.selectId;
      var child = hardwareSelectItemsObj.child;
      var selectIdArrayT = new Array();
      selectIdArrayT = selectIdArrayT.concat(selectIdArray);
      if (nextSelectId == selectId) {
        return selectIdArrayT;
      } else {
        selectIdArrayT.push(selectId);
        return getSelectDisabledIds(nextSelectId, child, selectIdArrayT);
      }

    }
    /**
     * 清空所有下级select
     * @param currentSelectId 当前select
     * @param hardwareSelectItemsObj 配置项
     */
    function emptyNextsSelect(currentSelectId, hardwareSelectItemsObj) {
      var selectId = hardwareSelectItemsObj.selectId;
      var child = hardwareSelectItemsObj.child;

      if (currentSelectId == selectId) {

        if (typeof(child) == "undefined") {

        } else {
          emptyNextsSelectTow(child);
        }



      } else {
        emptyNextsSelect(currentSelectId, child);
      }

    }
    // 清空所有下级select
    function emptyNextsSelectTow(hardwareSelectItemsObj) {
      var selectId = hardwareSelectItemsObj.selectId;
      var child = hardwareSelectItemsObj.child;
      $('#' + selectId).attr("disabled", false);
      $("#" + selectId).empty().html('<option value="">请选择,可输入关键字检索</option>');

      if (typeof(child) == "undefined") {
        return;
      } else {
        emptyNextsSelectTow(child);
      }

    }
    //点击确认按钮
    function okClick() {
      //下拉框获取,得到需要取数据的id；
      //var selectId = getValueId(initjson.hardwareSelectItems);
      //下拉框获取
      //var selectText =  $("#"+selectId).find("option:selected").text();
      //var selectValue = $("#"+selectId).val().split("##")[0];
      //单选框获取
      var selectText = $('input[name="sensor"]:checked').attr('title');
      var selectValue = $('input[name="sensor"]:checked').val().split("##")[0];
      //console.log(selectText,selectValue);
      if (selectValue) {
        parent.hardware_id = selectValue;
        parent.hardware_Text = selectText;
      } else { //可以为空，用以清除绑定
        parent.hardware_id = "";
        parent.hardware_Text = "";
        //console.log("a");
      }
      parent.layer.close(index);
    }
    //得到需要取数据的selectId
    function getValueId(hardwareSelectItemsObj) {
      var selectId = hardwareSelectItemsObj.selectId;
      var child = hardwareSelectItemsObj.child;
      var valueFlag = hardwareSelectItemsObj.valueFlag;
      if (valueFlag) {
        return selectId;
      } else {
        return getValueId(child);
      }

    }
  </script>
</html>
